import React, { PropTypes, PureComponent } from 'react';
import {connect} from 'dva';
import { routerRedux } from 'dva/router';
import {Row, Col, Button, Spin} from 'antd';
import queryString from 'query-string';
import styles from './index.css';
import IssueModal from './IssueModal'
import Markdown from '@/components/Markdown';
@connect(({article}) => ({
  ...article,
  namespace:'article',
}))
export default class Issue extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      content:'',
      title:'',
      init:true,
      type:'1',
      originalUrl:null,
      digest:null,
      classification:'',
      author:"",
      id:null,
    }
  }

  componentWillMount() {
    const {record = {}, dispatch, namespace} = this.props;
    const {location: { search }} = this.props;
    const query = queryString.parse(search);
    if(query.id) {
      //如果存在，则去请求
      dispatch({type:`${namespace}/queryById`, payload:query.id}).then((response) => {
        if(response) {
          const {data:{title, content, originalUrl, digest, type, author, classification, id}} = response;
          this.setState({
            title,
            content,
            type:type || '1',
            originalUrl,
            digest,
            classification,
            author,
            id,
            init: false,
          });
        }
      })
    } else {
      this.setState({
        init: false,
      });
    }

  }

  render() {
    const { content, title, init } = this.state;
    if(init) {
      return (
        <Spin tip="初始化中，请稍后..." style={{ marginTop: '20%' }}>
					<div style={{ width: '100%', background: 'rgba(50,50,50, 0.1)' }}></div>
				</Spin>
      )
    }
    return (
      <div className={styles.issue}>
        <div className={styles.title}>
          <Row>
            <Col className="gutter-row" span={18}>
              <input ref={(input) => this.input = input} defaultValue={title} onChange={(e) => this.setState({ title: e.target.value })} placeholder="文章标题..." className={styles.titleInput} />
            </Col>
            <Col className="gutter-row" span={6} className={styles.option}>
              <Button type="default" size="default" icon="rollback" onClick={() => this.props.dispatch(routerRedux.push({pathname: '/blog/article'}))}>返回列表</Button>
              <IssueModal record={this.state} dispatch={this.props.dispatch} namespace={this.props.namespace} option='create' loading={this.props.loading} title="博文确认">
                <Button icon='plus-circle-o' type="primary" size="default">提交</Button>
              </IssueModal>
            </Col>
          </Row>
        </div>
        <div className={styles.textarea} style={{height: 'calc(100vh - 145px)'}}>
          <Markdown defaultValue={content} onChange = {(value) => this.setState({content:value})}/>
        </div>
      </div>
    )
  }
}
